package com.sgb.member.ui.fragment;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ProgressBar;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.GridLayoutManager;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.google.android.material.appbar.AppBarLayout;
import com.google.android.material.tabs.TabLayout;
import com.sgb.member.MemberConfig;
import com.sgb.member.R;
import com.sgb.member.databinding.FragmentMainMemberBinding;
import com.sgb.member.di.DaggerMemberFragComponent;
import com.sgb.member.di.MemberFragModule;
import com.sgb.member.entity.AppIcon;
import com.sgb.member.event.EventConstant;
import com.sgb.member.event.MenuEvent;
import com.sgb.member.ui.activity.ClientDynamicStateActivity;
import com.sgb.member.ui.activity.ClientPerformanceActivity;
import com.sgb.member.ui.activity.ClientPropertyActivity;
import com.sgb.member.ui.activity.ClientQualificationActivity;
import com.sgb.member.ui.activity.MemberAuditActivity;
import com.sgb.member.ui.activity.MemberBusinessActivity;
import com.sgb.member.ui.activity.MemberInviteOrApplyActivity;
import com.sgb.member.ui.activity.MemberManageActivity;
import com.sgb.member.ui.activity.MemberOpportunityActivity;
import com.sgb.member.ui.activity.RemoveMemberActivity;
import com.sgb.member.ui.adapter.HomeMemberMenuAdapter;
import com.sgb.member.view_model.HomeMemberModel;
import com.swgk.core.base.AppLazyFragment;
import com.swgk.core.base.aroute.SimpleARouteCallback;
import com.swgk.core.base.di.AppComponent;
import com.swgk.core.customview.XCustomTabLayout;
import com.swgk.core.dialog.DialogHelper;
import com.swgk.core.event.MessageEvent;
import com.swgk.core.mmkvutil.CacheMarker;
import com.swgk.core.mmkvutil.MkvUtils;
import com.swgk.core.recyclerview.adapter.SlidingFragmentPagerAdapter;
import com.swgk.core.refresh.SuperSwipeRefreshLayout;
import com.swgk.core.util.MLog;
import com.swgk.core.util.SharedPreferenceUtil;
import com.swgk.core.view.entity.EnterpriseEditEntity;
import com.swgk.core.view.selection.CommonPopEntity;
import com.swgk.core.view.weiget.BigHomeComparyWidget;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

/**
 * 会员首页
 */
@Route(path = MemberConfig.ROUTE_MAIN_FRAGMENT)
public class HomeMemberFragment extends AppLazyFragment implements SuperSwipeRefreshLayout.OnPullRefreshListener {

    @Inject
    HomeMemberModel mModel;
    private FragmentMainMemberBinding mBinding;

    private ArrayList<Fragment> mFragments;
    private boolean isRecommendMember; // 是否推荐会员
    private boolean isPersonCenter; // 是否个人

    private String mTempCompanyNo = "-1";
    private HomeMemberMenuAdapter menuAdapter;

    public static HomeMemberFragment newInstance() {
        HomeMemberFragment fragment = new HomeMemberFragment();
        Bundle bundle = new Bundle();
        fragment.setArguments(bundle);
        return fragment;
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        mBinding = DataBindingUtil.inflate(inflater, R.layout.fragment_main_member, container, false);
        return mBinding.getRoot();
    }

    @Override
    protected void setupFragmentComponent(AppComponent appComponent) {
        DaggerMemberFragComponent.builder()
                .appComponent(appComponent)
                .memberFragModule(new MemberFragModule(this))
                .build()
                .inject(this);
    }

    @Override
    protected void initView() {
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
        mBinding.setViewModel(mModel);
        // 刷新
        mBinding.swipeRefresh.setOnPullRefreshListener(this);
        mBinding.appBarLayout.addOnOffsetChangedListener(new AppBarLayout.OnOffsetChangedListener() {
            @Override
            public void onOffsetChanged(AppBarLayout appBarLayout, int i) {
                mBinding.swipeRefresh.setEnabled(i >= 0);
            }
        });
        mBinding.swipeRefresh.setLoadMore(false);
        mBinding.swipeRefresh.setHeaderView(createHeaderView());
        mBinding.ivQuickEntry.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                MessageEvent messageEvent = new MessageEvent();
//                messageEvent.code = 2021;
//                messageEvent.data = "选首页";
//                EventBus.getDefault().postSticky(messageEvent);
            }
        });
    }


    private SimpleARouteCallback callback = new SimpleARouteCallback() {
        @Override
        public void onResult(Object... objects) {
            if (objects.length == 2) {
                String longitude = (String) objects[0];
                String latitude = (String) objects[1];
                if (!TextUtils.isEmpty(longitude)) {
                    SharedPreferenceUtil.getInstance().saveString(SharedPreferenceUtil.LATITUDE_ID, longitude);
                }
                if (!TextUtils.isEmpty(latitude)) {
                    SharedPreferenceUtil.getInstance().saveString(SharedPreferenceUtil.LONGITUDE_ID, latitude);
                }
            }
        }
    };

    @Override
    protected void onLazyLoad() {
        Log.d("HomeMemberFragment", "onLazyLoad");
        mModel.getMenuList();
        //获取首页企业推荐
        mTempCompanyNo = SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.COMPANY_NO, "");
        getAccountMemberSize();
        String lat = SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.LATITUDE_ID, "");
        String lon = SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.LONGITUDE_ID, "");
        if (lat.equals("0.0") || lon.equals("0.0")) {
            getLocation();
        }
    }

    private void getLocation() {
        MemberConfig.getInstance().getLocalPosition(requireContext(), new SimpleARouteCallback() {
            @Override
            public void onResult(Object... objects) {
                try {
                    if (objects.length == 2) {
                        String longitude = (String) objects[0];
                        String latitude = (String) objects[1];
                        if (!TextUtils.isEmpty(longitude)) {
                            SharedPreferenceUtil.getInstance().saveString(SharedPreferenceUtil.LATITUDE_ID, longitude);
                        }
                        if (!TextUtils.isEmpty(latitude)) {
                            SharedPreferenceUtil.getInstance().saveString(SharedPreferenceUtil.LONGITUDE_ID, latitude);
                        }
                    }
                } catch (Exception e) {

                }
            }
        });
    }

    @Override
    public void onVisible() {
        Log.d("HomeMemberFragment", "onVisible");
        //获取首页企业推荐
        mModel.getCompanyTitleList("会员刷新 onVisible");
        String companyNo = SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.COMPANY_NO, "");
        if (mBinding != null && !TextUtils.equals(mTempCompanyNo, companyNo)) {
            mTempCompanyNo = companyNo;
            getAccountMemberSize();
        }
        mModel.getPermissionHuiYuan();
    }

    private void getAccountMemberSize() {
        boolean isRecommendMember = TextUtils.isEmpty(SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.LOGIN_TOKEN, ""));
        // 类型 0个人 1企业 2团队
        int comType = SharedPreferenceUtil.getInstance().getSaveIntData(SharedPreferenceUtil.COM_TYPE, 0);
        if (isRecommendMember) {
            initViewPager(false, false);
        } else {
            String userNo = SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.USER_NO, "");
            // type：1 企业 2个人
            mModel.getAccountMemberSize(comType == 0 ? 2 : 1, comType == 0 ? userNo : mTempCompanyNo);
        }
    }

    String[] mTabs;

    /**
     * @param personCenter 是否为个人中心
     * @param hasMember    是否有会员
     */
    public void initViewPager(boolean personCenter, boolean hasMember) {
        if (getActivity() != null && !DialogHelper.isShowing()) {
            DialogHelper.showProgressDialog(getActivity(), "数据加载中...");
        }
        mBinding.viewPager.setVisibility(View.VISIBLE);
        mBinding.viewPager.removeAllViews();
        mBinding.viewPager.clearOnPageChangeListeners();
        mBinding.tabLayout.removeAllTabs();
        mFragments = new ArrayList<>();
        isPersonCenter = personCenter;
        if (hasMember) {
            isRecommendMember = false;
            mBinding.tvRecommend.setVisibility(View.GONE);
            mBinding.tabLayout.setVisibility(View.VISIBLE);
//            if (personCenter) {
//                mTabs = new String[]{"供方会员", "需方会员"};
//                mBinding.tabLayout.setTabMode(TabLayout.MODE_FIXED);
//                for (int i = 0; i < mTabs.length; i++) {
//                    CommonPopEntity entity = new CommonPopEntity(i + "", mTabs[i]);
//                    mFragments.add(HomePersonMemberFragment.newInstance(i, entity));
//                }
//            } else {
            mTabs = new String[]{"供方会员", "需方会员", "会员招采", "会员商品", "会员集采", "会员租赁", "会员工队", "会员物流", "会员企服"};
            mBinding.tabLayout.setTabMode(TabLayout.MODE_SCROLLABLE);
            for (int i = 0; i < mTabs.length; i++) {
                CommonPopEntity entity = new CommonPopEntity(i + "", mTabs[i]);
                if (mTabs[i].equals("会员企服")) {
                    mFragments.add(new CompanyServiceFragment());
                } else if (mTabs[i].equals("会员招采")) {
                    mFragments.add(new ZhaoCaiServiceFragment());
                } else {
                    mFragments.add(HomeOtherMemberFragment.newInstance(i, entity));
                }
            }
//            }
            mBinding.viewPager.setOffscreenPageLimit(mTabs.length);
            if (mBinding.viewPager.getAdapter() == null) {
                SlidingFragmentPagerAdapter adapter = new SlidingFragmentPagerAdapter(getChildFragmentManager(), mFragments, mTabs);
                mBinding.viewPager.setAdapter(adapter);
            } else {
                ((SlidingFragmentPagerAdapter) mBinding.viewPager.getAdapter()).setFragments(mFragments, mTabs);
            }
            mBinding.tabLayout.setupWithViewPager(mBinding.viewPager);
            mBinding.tabLayout.setNormalColor(R.color.color_333333);
            mBinding.tabLayout.addOnTabSelectedListener(mTabs, new XCustomTabLayout.SimpleSelectedListener() {
                @Override
                public void onTabSelected(TabLayout.Tab tab) {
                    mBinding.viewPager.setCurrentItem(tab.getPosition());
                }
            });
        } else {
            isRecommendMember = true;
            // "优质企业推荐",
            mTabs = new String[]{"优质企业推荐"};
            mBinding.tvRecommend.setVisibility(View.VISIBLE);
            mBinding.tabLayout.setVisibility(View.GONE);
            mFragments.add(HomeQualityMemberFragment.newInstance(0));
            if (mBinding.viewPager.getAdapter() == null) {
                SlidingFragmentPagerAdapter adapter = new SlidingFragmentPagerAdapter(getChildFragmentManager(), mFragments, mTabs);
                mBinding.viewPager.setAdapter(adapter);
                mBinding.viewPager.setOffscreenPageLimit(1);
            } else {
                ((SlidingFragmentPagerAdapter) mBinding.viewPager.getAdapter()).setFragments(mFragments, mTabs);
            }
        }
        mBinding.viewPager.setCurrentItem(0, false);
    }

    private List<AppIcon> icons;

    public void refreshMenus2(List<AppIcon> data) {
        if (data == null || data.size() == 0) {
            closeRecyclerRefreshing();
            return;
        }
        icons = data;
        menuAdapter = new HomeMemberMenuAdapter(requireContext(), data, bean -> {
            extracted(bean);
            return null;
        });

        mBinding.rvMenu.setLayoutManager(new GridLayoutManager(requireContext(), 5));
        mBinding.rvMenu.setAdapter(menuAdapter);
    }

    private void extracted(AppIcon entity) {
        boolean isEmpty = "".equals(SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.LOGIN_TOKEN, ""));
        if (isEmpty) {
            MemberConfig.getInstance().startVerificationCodeLogin(getActivity(), EventConstant.EVENT_HOME_MEMBER_FRG_JUMP);
        } else {
            switch (entity.getCode()) {
                case "membermanagement":  // 会员管理
                    MemberManageActivity.start(getActivity());
                    return;
                case "manageMentBusinessOpportunity":  // 会员商机
                    MemberOpportunityActivity.start(getActivity());
                    return;
                case "memberManageMentBusiness":  // 会员经营
                    //   MemberOperationsActivity.start(getActivity());
                    MemberBusinessActivity.start(getActivity());
                    return;
                case "memberPerformanceCertificate":    // 会员业绩
                    ClientPerformanceActivity.start(getActivity());
                    return;
                case "memberAsset":  // 会员资质
                    ClientQualificationActivity.start(getActivity());
                    return;
                case "memberQualifications":  // 会员资产
                    ClientPropertyActivity.start(getActivity());
                    return;
                case "companyNews":  // 会员动态
                    ClientDynamicStateActivity.start(getActivity());
                    return;
            }
            if (!MemberConfig.getInstance().isPermission()) {
                MemberConfig.getInstance().showACDialog(getActivity());
            } else {
                switch (entity.getCode()) {
                    case "invitedMember": //邀请会员
                        MemberInviteOrApplyActivity.startInviteOrApply(getActivity(), 0);
                        break;
                    case "applyMember": //申请加盟
                        MemberInviteOrApplyActivity.startInviteOrApply(getActivity(), 1);
                        break;
                    case "invitedRecord": //邀请记录
                        MemberInviteOrApplyActivity.startInviteOrApplyRecord(getActivity(), 0);
                        break;
                    case "applyRecord": // 申请记录
                        MemberInviteOrApplyActivity.startInviteOrApplyRecord(getActivity(), 1);
                        break;
                    case "memberCheck": // 会员审核
                        MemberAuditActivity.start(getActivity());
                        break;
                }
            }
        }
    }

    @Override
    public void onRefresh() {
        textView.setText("正在刷新");
        if (icons == null || icons.size() == 0) {
            mModel.getMenuList();
        }
        //获取首页企业推荐
        loadData(false);
    }

    private void loadData(boolean isLoadMore) {
        if (mFragments == null || mFragments.size() == 0) {
            closeRecyclerRefreshing();
            DialogHelper.dismissProgressDialog();
            return;
        }
        if (isRecommendMember) {
            Fragment fragment = mFragments.get(0);
            if (fragment instanceof HomeQualityMemberFragment) {
                ((HomeQualityMemberFragment) fragment).loadData(isLoadMore);
            }
        } else {
            Fragment fragment = mFragments.get(mBinding.tabLayout.getSelectedTabPosition());
//            if (isPersonCenter) {
//                if (null != fragment && fragment instanceof HomePersonMemberFragment) {
//                    ((HomePersonMemberFragment) fragment).refreshTabData();
//                }
//            } else {
            if (null != fragment && fragment instanceof HomeOtherMemberFragment) {
                ((HomeOtherMemberFragment) fragment).refreshTabData();
            }
            if (null != fragment && fragment instanceof CompanyServiceFragment) {
                ((CompanyServiceFragment) fragment).refreshTabData();
            }
            if (null != fragment && fragment instanceof ZhaoCaiServiceFragment) {
                ((ZhaoCaiServiceFragment) fragment).refreshTabData();
            }
//            }

        }
    }

    @Override
    public void onPullDistance(int distance) {

    }

    @Override
    public void onPullEnable(boolean enable) {
        textView.setText(enable ? "释放立即刷新" : "下拉刷新");
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(MenuEvent event) {
        if (event.getMessageTag() == EventConstant.EVENT_MENU_POWER) {
            MLog.d("api", event.getNo());
            // PowerListActivity.start(getActivity(), event.getNo(), event.getChildNo());
        }
    }

//    /**
//     * event监听登录和登出的状态
//     */
//    @Subscribe(threadMode = ThreadMode.MAIN)
//    public void onEvent(LoginEvent event) {
//        if (event.getMessageTag() == EventConstant.EVENT_LOGIN_OUT) {
//            // 手动设置置空
//            SharedPreferenceUtil.getInstance().saveData(SharedPreferenceUtil.COMPANY_NO, "");
//            chooseTab();
//        } else if (event.getMessageTag() == EventConstant.EVENT_LOGIN) {
//            chooseTab();
//        }
//    }

    public void closeRecyclerRefreshing() {
        mBinding.swipeRefresh.setRefreshing(false);
        mBinding.swipeRefresh.setLoadMore(false);
    }

    private TextView textView;

    private View createHeaderView() {
        @SuppressLint("InflateParams")
        View headerView = LayoutInflater.from(mBinding.swipeRefresh.getContext()).inflate(R.layout.super_swipe_refresh_head, null);
        ProgressBar progressBar = headerView.findViewById(R.id.pb_view);
        textView = headerView.findViewById(R.id.text_view);
        textView.setText("下拉刷新");
        progressBar.setVisibility(View.GONE);
        return headerView;
    }


    @Override
    public void onDestroy() {
        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }

    /**
     * 初始化首页企业推荐界面
     */
    public void initCompanyTitle(List<EnterpriseEditEntity> data) {
        if (mBinding == null) return;
        vsCompany = mBinding.vsCompany.getViewStub();
        if (vsCompany != null)
            vsCompany.inflate();
        if (vsCompany != null) {
            inflatedCompany = mBinding.getRoot().findViewById(R.id.inflatedCompany);
            bigHomeCompary = new BigHomeComparyWidget(this, inflatedCompany);
        }
        if (bigHomeCompary != null) {
            bigHomeCompary.unInit();
        }
        if (data == null || data.size() == 0) return;
        bigHomeCompary.initData(data);
        boolean isType = MkvUtils.get().getBoolean(MkvUtils.CommomData, CacheMarker.DisplaySettingsType, true);
        boolean isQY = MkvUtils.get().getBoolean(MkvUtils.CommomData, CacheMarker.DisplaySettingsQY, true);
        bigHomeCompary.setIsAotu(isType, isQY);
    }
}
